package com.pf.java.File;

import java.io.*;

/**
 * transient关键字
 *
 * ClassName:IO13
 * Package:com.pf.java.File
 *
 * @author: pf
 * @date: 2021/11/8-16:34
 */
public class IO13 {

    public static void main(String[] args) {
        testSerialize();
        testDeserialize();
    }

    /**
     * 序列化
     */
    public static void testSerialize() {
        try (
                ObjectOutputStream oos = new ObjectOutputStream(
                        new FileOutputStream("C:/Users/10970/Desktop/Java学习笔记/牛客网学习/user.txt")
                );
        ){
            User user =new User("John", "123456");
            user.setEmail("sss@email.com");
            user.setPhone("111222333444");
            oos.writeObject(user);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 反序列化
     */
    public static void testDeserialize() {
        try (
                ObjectInputStream ois = new ObjectInputStream(
                        new FileInputStream("C:/Users/10970/Desktop/Java学习笔记/牛客网学习/user.txt")
                );
        ){
            System.out.println(ois.readObject());

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }


}

class User implements Serializable {

    private static final long serialVersionUID = -9041595212991562236L;
    private String username;
    private transient String password;// 不希望该变量被序列化使用关键字transient
    private String email;
    private String phone;

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                ", phone='" + phone + '\'' +
                '}';
    }
}